<template>
  <div class="register-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="用户注册"
      left-text="返回"
      left-arrow
      @click-left="handleBack"
      :border="false"
      :fixed="true"
      :placeholder="true"
      :z-index="1000"
    />

    <!-- 主要内容 -->
    <div class="register-content">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo">
          <van-icon name="volume-o" size="60" color="#1989fa" />
        </div>
        <h1 class="app-title">普通话学习</h1>
        <p class="app-subtitle">创建您的学习账户</p>
      </div>

      <!-- 注册表单 -->
      <div class="form-section">
        <van-form @submit="handleSubmit" ref="formRef">
          <van-cell-group inset>
            <van-field
              v-model="formData.username"
              name="username"
              label="用户名"
              placeholder="请输入用户名"
              :rules="[
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名至少3个字符' },
                { max: 20, message: '用户名最多20个字符' }
              ]"
              left-icon="user-o"
              clearable
            />

            <van-field
              v-model="formData.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              :rules="[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
              ]"
              left-icon="phone-o"
              clearable
            />

            <!-- <van-field
              v-model="formData.verificationCode"
              name="verificationCode"
              label="验证码"
              placeholder="请输入验证码"
              :rules="[
                { required: true, message: '请输入验证码' },
                { len: 6, message: '验证码为6位数字' }
              ]"
              left-icon="shield-o"
              clearable
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  :disabled="codeDisabled"
                  @click="sendCode"
                  :loading="sendingCode"
                >
                  {{ codeText }}
                </van-button>
              </template>
            </van-field> -->

            <van-field
              v-model="formData.password"
              name="password"
              type="password"
              label="密码"
              placeholder="请输入密码"
              :rules="[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码至少6个字符' },
                { max: 20, message: '密码最多20个字符' }
              ]"
              left-icon="lock"
              clearable
            />

            <van-field
              v-model="formData.confirmPassword"
              name="confirmPassword"
              type="password"
              label="确认密码"
              placeholder="请再次输入密码"
              :rules="[
                { required: true, message: '请确认密码' },
                { validator: validateConfirmPassword }
              ]"
              left-icon="lock"
              clearable
            />
          </van-cell-group>

          <!-- 用户协议 -->
          <div class="agreement-section">
            <van-checkbox v-model="agreeTerms">
              我已阅读并同意
              <span class="link-text" @click="showTerms">《用户协议》</span>
              和
              <span class="link-text" @click="showPrivacy">《隐私政策》</span>
            </van-checkbox>
          </div>

          <!-- 注册按钮 -->
          <div class="button-section">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              :disabled="!agreeTerms"
              size="large"
            >
              立即注册
            </van-button>
          </div>
        </van-form>

        <!-- 登录链接 -->
        <div class="login-link">
          <span>已有账户？</span>
          <span class="link-text" @click="goToLogin">立即登录</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { AuthService } from '@/api/services';

const router = useRouter();
const formRef = ref();

// 表单数据
const formData = reactive({
  username: '',
  phone: '',
  verificationCode: '',
  password: '',
  confirmPassword: '',
});

const loading = ref(false);
const agreeTerms = ref(false);
const sendingCode = ref(false);
const countdown = ref(0);

// 验证码相关
const codeDisabled = computed(() => {
  return countdown.value > 0 || !formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone);
});

const codeText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s后重发` : '发送验证码';
});

// 确认密码验证
const validateConfirmPassword = (value: string) => {
  if (value !== formData.password) {
    return '两次输入的密码不一致';
  }
  return true;
};

// 发送验证码
const sendCode = async () => {
  if (!formData.phone) {
    showToast('请输入手机号');
    return;
  }

  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    showToast('请输入正确的手机号');
    return;
  }

  try {
    sendingCode.value = true;
    const result = await AuthService.sendVerificationCode(formData.phone);

    if (result) {
      showToast('验证码已发送');
      // 开始倒计时
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    }
  } catch (error) {
    showToast('发送验证码失败');
  } finally {
    sendingCode.value = false;
  }
};

// 处理注册提交
const handleSubmit = async (values: any) => {
  if (!agreeTerms.value) {
    showToast('请先同意用户协议和隐私政策');
    return;
  }

  loading.value = true;

  try {
    const result = await AuthService.register({
      username: values.username,
      nickname: values.username, // 使用用户名作为昵称
      phone: values.phone,
      verifyCode: values.verificationCode,
      password: values.password
    });

    if (result) {
      showToast('注册成功');

      // 延迟跳转到登录页
      setTimeout(() => {
        router.replace('/login');
      }, 1500);
    }
  } catch (error) {
    showToast('注册失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 跳转到登录页
const goToLogin = () => {
  router.replace('/login');
};

// 显示用户协议
const showTerms = () => {
  showDialog({
    title: '用户协议',
    message: '这里是用户协议的内容...',
    confirmButtonText: '我知道了'
  });
};

// 显示隐私政策
const showPrivacy = () => {
  showDialog({
    title: '隐私政策',
    message: '这里是隐私政策的内容...',
    confirmButtonText: '我知道了'
  });
};
</script>

<style lang="scss" scoped>
.register-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.register-content {
  padding: 5.33333vw;
  padding-top: 21.33333vw; // 为导航栏留空间
}

.logo-section {
  text-align: center;
  margin-bottom: 10.66667vw;

  .logo {
    margin-bottom: 5.33333vw;
  }

  .app-title {
    font-size: 8vw;
    font-weight: bold;
    color: #323233;
    margin: 0 0 2.66667vw 0;
  }

  .app-subtitle {
    font-size: 3.73333vw;
    color: #969799;
    margin: 0;
  }
}

.form-section {
  .van-cell-group {
    margin-bottom: 5.33333vw;
  }
}

.agreement-section {
  padding: 4.26667vw 0;
  text-align: center;

  .link-text {
    color: #1989fa;
    text-decoration: none;

    &:active {
      opacity: 0.7;
    }
  }
}

.button-section {
  margin: 8vw 0;
}

.login-link {
  text-align: center;
  font-size: 3.73333vw;
  color: #646566;

  .link-text {
    color: #1989fa;
    margin-left: 1.33333vw;

    &:active {
      opacity: 0.7;
    }
  }
}

// 响应式设计
@media (min-width: 768px) {
  .register-content {
    max-width: 400px;
    margin: 0 auto;
    padding-top: 80px;
  }

  .logo-section {
    .app-title {
      font-size: 32px;
    }

    .app-subtitle {
      font-size: 14px;
    }
  }

  .agreement-section,
  .login-link {
    font-size: 14px;
  }
}
</style>